const util = require('../../utils/util')
const app = getApp();
Page({
  data: {
    cameraPosition: 'back', // 摄像头位置：back/front
    hasPhoto: false, // 是否有拍摄的照片
    photoPath: '', // 照片路径
    currentTime: '', // 当前时间
    locationName: '获取位置中...', // 位置名称
    remark: '编辑备注信息',
    latitude: 0, // 纬度
    longitude: 0, // 经度
    flash: 'off', // 闪光灯 on/off/auto
    index: -1,
    visible: false,
    textColor: '#FFFFFF'
  },

  onLoad(options) {
    // console.log(options.index);
    this.setData({
      index: options.index
    })
    // 初始化时间
    this.updateTime();
    setInterval(() => this.updateTime(), 1000);

    // 获取位置信息
    this.getLocation();
  },

  // 更新当前时间
  updateTime() {
    const date = new Date();
    // const timeStr = date.toLocaleString('zh-CN', {
    //   year: 'numeric',
    //   month: '2-digit',
    //   day: '2-digit',
    //   hour: '2-digit',
    //   minute: '2-digit',
    //   second: '2-digit'
    // });
    const timeStr = util.formatTime(date)
    this.setData({ currentTime: timeStr });
  },

  // 获取位置信息
  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        this.getAddress(res.latitude, res.longitude);
      },
      fail: () => {
        this.setData({ locationName: '位置获取失败' });
      }
    });
  },

  // 解析地址信息
  getAddress(lat, lon) {
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lon}&key=${app.globalData.MAP_KEY}`,
      success: (res) => {
        // console.log(res);
        if (res.data.status === 0) {
          this.setData({
            locationName: res.data.result.formatted_addresses.recommend
          });
        }
      },
      fail: () => {
        this.setData({ locationName: '地址解析失败' });
      }
    });
  },
  onEdit() {
    wx.showModal({
      title: '请输入',
      placeholderText: '自定义信息',
      editable: true,
      content: this.data.remark,
      complete: (res) => {
        // console.log(res);

        if (res.cancel) {

        }
        if (res.confirm) {
          this.setData({
            remark: res.content
          })
        }
      }
    })
  },
  // 切换闪光灯
  toggleFlash() {
    const currentFlash = this.data.flash;
    let newFlash;

    if (currentFlash === 'off') {
      newFlash = 'on';
    } else if (currentFlash === 'on') {
      newFlash = 'auto';
    } else {
      newFlash = 'off';
    }

    this.setData({
      flash: newFlash
    });
  },
  // 切换摄像头
  switchCamera() {
    this.setData({
      cameraPosition: this.data.cameraPosition === 'back' ? 'front' : 'back'
    });
  },

  // 拍摄照片
  takePhoto() {
    const ctx = wx.createCameraContext();
    const that = this;
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        // console.log(res);
        // that.setData({
        //   photoPath: res.tempImagePath,
        //   hasPhoto: true
        // })
        that.drawWatermark(res.tempImagePath);
      },
      fail(err) {
        console.log(err);
      }
    });
  },

  // 绘制水印
  drawWatermark(imagePath) {
    const that = this;
    const index = that.data.index;
    // 获取图片信息
    wx.getImageInfo({
      src: imagePath,
      success: (imgInfo) => {
        // console.log(imgInfo);
        const canvasWidth = imgInfo.width;
        const canvasHeight = imgInfo.height;

        // 设置canvas尺寸
        const query = wx.createSelectorQuery();
        query.select('#watermarkCanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');

            // 设置canvas尺寸
            canvas.width = canvasWidth;
            canvas.height = canvasHeight;

            // 绘制原图
            const image = canvas.createImage();
            image.src = imagePath;
            image.onload = () => {
              ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
              console.log(that.data.textColor);
              // 设置水印样式
              ctx.fillStyle = that.data.textColor;
              ctx.font = '30px sans-serif';
              ctx.textAlign = 'center';
              // ctx.shadowColor = 'black';
              // ctx.shadowBlur = 2;

              // if (index === '0') {
              //   // 绘制时间水印
              //   ctx.fillText(that.data.currentTime, canvasWidth / 2, canvasHeight - 160);
              //   // 绘制位置水印
              //   ctx.fillText(that.data.locationName, canvasWidth / 2, canvasHeight - 120);
              //   // 绘制自定义水印
              //   ctx.fillText(that.data.remark, canvasWidth / 2, canvasHeight - 80);
              // } else if (index === '1') {
              //   ctx.fillText(that.data.currentTime, canvasWidth / 2, canvasHeight - 160);
              // } else if (index === '2') {
              //   ctx.fillText(that.data.locationName, canvasWidth / 2, canvasHeight - 120);
              // } else if (index === '3') {
              //   ctx.fillText(that.data.remark, canvasWidth / 2, canvasHeight - 80);
              // }
              let text = '';
              let remark = that.data.remark === '编辑备注信息' ? '' : that.data.remark;
              let yPoint=80;
              if (index === '0') {
                yPoint=160;
                text = `${that.data.currentTime}\n${that.data.locationName}\n${remark}`
              } else if (index === '1') {
                text = `${that.data.currentTime}`
              } else if (index === '2') {
                text = `${that.data.locationName}`
              } else if (index === '3') {
                text = `${remark}`
              }
              drawLongText(
                ctx,
                text,
                canvasWidth / 2, // X坐标（居中）
                canvasHeight - yPoint, // 起始Y坐标
                canvasWidth - 20, // 最大宽度（左右各留20px边距）
                40 // 行高（根据字体大小调整）
              );


              // 转换为图片
              setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvas,
                  success: (res) => {
                    that.setData({
                      photoPath: res.tempFilePath,
                      hasPhoto: true
                    });
                  }
                });
              }, 100);
            };
          });
      }
    });
  },

  // 重新拍摄
  reTakePhoto() {
    this.setData({
      hasPhoto: false,
      photoPath: ''
    });
  },
  usePhoto() {

  },
  // 保存图片到相册
  savePhoto() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.photoPath,
      success: () => {
        wx.showToast({ title: '保存成功' });
      },
      fail: () => {
        wx.showToast({ title: '保存失败', icon: 'none' });
      }
    });
  },
  openColorPicker() {
    this.setData({
      visible: true
    })
  },
  change(e) {
    console.log(e.detail.value);
    this.setData({
      textColor: e.detail.value
    })
  },
  // 相机错误处理
  cameraError(e) {
    console.error('相机错误:', e.detail);
    wx.showToast({ title: '相机初始化失败', icon: 'none' });
  },
  onShareAppMessage() {

  },
  onShareTimeline() {

  }
});

// 在 canvas 绘制上下文（ctx）中执行
function drawLongText(ctx, text, x, y, maxWidth, lineHeight) {
  if (!text) return;

  // 先按换行符分割成多个段落
  const paragraphs = text.split('\n');

  paragraphs.forEach(paragraph => {
    if (paragraph === '') {
      // 空行处理，直接换行
      y += lineHeight;
      return;
    }

    let currentText = ''; // 当前行文字
    const textArr = paragraph.split(''); // 拆分成单个字符

    // 遍历每个字符，判断是否需要换行
    for (let i = 0; i < textArr.length; i++) {
      const char = textArr[i];
      const tempText = currentText + char;
      // 计算临时文本的宽度
      const textWidth = ctx.measureText(tempText).width;

      // 如果临时文本宽度超过最大宽度，换行绘制
      if (textWidth > maxWidth) {
        // 绘制当前行
        ctx.fillText(currentText, x, y);
        // 重置当前行，Y坐标下移一行
        currentText = char;
        y += lineHeight;
      } else {
        // 否则继续拼接文字
        currentText = tempText;
      }
    }

    // 绘制最后一行剩余文字
    if (currentText) {
      ctx.fillText(currentText, x, y);
    }

    // 段落结束后换行
    y += lineHeight;
  });
}
